package edu.thu.studio.ormdesigner.persistent;

import java.lang.reflect.Field;

import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;

public class AnnotationJavaReflectionProvider extends PureJavaReflectionProvider {
    
    /**
     * 写字段时验证字段可以被访问，且对于String类型需要进行trim
     */
    @Override
    public void writeField(Object object, String fieldName, Object value, @SuppressWarnings("rawtypes") Class definedIn) {
        Field field = fieldDictionary.field(object.getClass(), fieldName, definedIn);
        validateFieldAccess(field);
        try {
            if (value instanceof String)
                field.set(object, ((String) value).trim());
            else
                field.set(object, value);
        } catch (IllegalArgumentException e) {
            throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e);
        } catch (IllegalAccessException e) {
            throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e);
        }
    }
}